# To change this template, choose Tools | Templates
# and open the template in the editor.


import sys, os, re
import urllib
from baseHandler import *
import simplejson

__author__="aalsum"
__date__ ="$Mar 6, 2013 12:07:59 PM$"

baseuri = "http://haw.nsk.hr/json.php?"

class CroatianHandler(BaseProxyHandler):

    def fetch_changes(self, req, requri, dt=None):
        # implement the changes list for this particular proxy

        parameters = {}
        parameters['q'] = requri
        parameters['subject'] = 'url'

        uri = baseuri + urllib.urlencode(parameters)
        try:
            fh = urllib.urlopen(uri)
        except:
            return self.error("Couldn't retrieve data from %s" % uri, req, status=404)


        jsonobj = simplejson.load(fh)

        fh.close()

        changes = []

        if int(jsonobj['availableHits'] )==0:
            return changes

        tmid = jsonobj['hits'][0]['ID']

        tmuri = "http://haw.nsk.hr/publikacija/"+tmid

        try:
            fh = urllib.urlopen(tmuri)
        except:
            return self.error("Couldn't retrieve data from %s" % uri, req, status=404)
        data = fh.read()
        fh.close()


        uriRegex =re.compile( r'<tr><td>[\d]*\.</td>.*</tr>');
        dtregex = re.compile('<td>\d\d\.\d\d\.\d\d\d\d[0-9\.:\s]*</td>')
         

        uris = re.findall(uriRegex, data)
        for u in uris:
            #print u
            d = u.index("title")
            loc = "http://haw.nsk.hr/"+u[45:d-2]

         #   print loc
            result = dtregex.search( u)
            if result:
               dtstr = result.group(0)
            dtstr= dtstr[4:-5]
 #           dtstr = u[49:63]
 #           loc = u[74:-2]
#01.12.2011 07:23:42


            dtstr=dtstr[6:10]+dtstr[3:5]+dtstr[0:2]+dtstr[11:19].replace(":","") + " GMT"
        #    print dtstr
            #dtstr += " GMT"
            dtobj = dateparser.parse(dtstr)
            changes.append((dtobj, loc, {'last': dtobj, 'obs' : 1}))

        return changes


def handler(req):
    hdlr = CroatianHandler('cr')
    return basehandler(req, hdlr)


